#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"

#include "hi_io.h" //==hi_io_set_func()、hi_io_set_pull()
#include "hi_gpio.h"
#include "hi_uart.h"
#include "iot_uart.h"
#include "speaker.h"

int Speaker_Init()
{
    hi_io_set_func(SPEAKER_RX_12, HI_IO_FUNC_GPIO_12_UART2_RXD);
    hi_io_set_func(SPEAKER_TX_11, HI_IO_FUNC_GPIO_11_UART2_TXD);

    hi_uart_attribute my_uart2;
    my_uart2.baud_rate = 115200;
    my_uart2.data_bits = 8;
    // my_uart1.pad = 0;
    my_uart2.parity = HI_UART_PARITY_NONE;
    my_uart2.stop_bits = 1;

    
    return hi_uart_init(HI_UART_IDX_2, &my_uart2, NULL);
}

int Speaker_read(char *get_data, int data_len)
{
    if(get_data ==NULL)
    {
        return -1;
    }
    int ret;
    // ret = hi_uart_read(HI_UART_IDX_1, get_data, data_len);
    ret = hi_uart_read_timeout(HI_UART_IDX_2, get_data, data_len, 10);
    return ret;
}

int Speaker_write(char *get_data, int data_len)
{
    if(get_data ==NULL)
    {
        return -1;
    }    
    int ret;
    ret = hi_uart_write_immediately(HI_UART_IDX_2, get_data, data_len);
    return ret;
}

/*
//测试语音模块
static void *SpeakerTask(void *arg)
{
    (void)arg;
    sleep(2);
    int ret = 1;
    ret = Speaker_Init();
    if (ret < 0)
    {
        printf("Uart2 init failed! \n");
        // return;
    }
    unsigned char send_data[] = {0xAA,0X55,0X09,0X20,0X06,0X55,0XAA};// 播报32.6℃
    char get_data[14]={0};
    while (1)
    {

        //usleep(500000); // 0.5s
        Speaker_read(get_data, 14);
        printf("Speaker read get_data:%s\n",get_data);

        //usleep(500000); // 0.5s
        ret = Speaker_write(send_data,14);
        if (ret >= 0)
            printf("send_data = %s\n", send_data);
        else
            printf("send get_data Failure\r\n");
        
        return NULL;
    }
}



static void SpeakerDemo(void)
{
    osThreadAttr_t attr;

    attr.name = "SpeakerTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = 31;

    if (osThreadNew(SpeakerTask, NULL, &attr) == NULL)
    {
        printf("[SpeakerDemo] Falied to create SpeakerTask!\n");
    }
}

//APP_FEATURE_INIT(SpeakerDemo);
//SYS_RUN(SpeakerDemo);

*/